package com.lhn.test;

import org.apache.http.HttpHost;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.RangeQueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.builder.SearchSourceBuilder;

import java.io.IOException;

/**
 * es 客户端-创建索引
 *
 * @author lhn
 * @date 2022/07/27 22:23
 * @since 1.0.0
 **/
public class ESTest_Doc_Query_Range {

    public static void main(String[] args) throws IOException {
        RestHighLevelClient restHighLevelClient = null;
        try {
            restHighLevelClient = new RestHighLevelClient(RestClient.builder(new HttpHost("106.15.191.175", 9200, "http")));

            // 查询数据
            SearchRequest searchRequest = new SearchRequest();
            searchRequest.indices("user");

            // 范围查询
            SearchSourceBuilder builder = new SearchSourceBuilder();
            RangeQueryBuilder rangeQuery = QueryBuilders.rangeQuery("age");

            rangeQuery.gt(30);

            builder.query(rangeQuery);
            searchRequest.source(builder);
            SearchResponse response = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);

            SearchHits hits = response.getHits();
            System.out.println(hits.getTotalHits());
            System.out.println(response.getTook());
            for (SearchHit hit : hits) {
                System.out.println(hit.getSourceAsString());
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            assert restHighLevelClient != null;
            restHighLevelClient.close();
        }
    }

}